<!-- 数据分析 -->
<template>
  <div class="newTest">
    <!-- 全屏弹出框 -->
    <el-dialog
      :visible.sync="detailChartVisible"
      width="80%"
      custom-class="historyChart"
      append-to-body
    >
      <div class="deatailChartCnt">
        <div class="deatailChart" id="deatailChart"></div>
      </div>
    </el-dialog>
    <!-- 日均值分析 -->
    <div class="dataChartCnt" v-loading="hisLoading">
      <div class="searchBox">
        <el-form
          label-position="top"
          inline
          :model="searchForm"
          size="mini"
          style="max-height: 100px"
        >
          <el-form-item>
            <p slot="label" class="miniLabel">水站名称</p>
            <el-select
              v-model="searchForm.watersmeantation"
              placeholder="请选择水站名称"
            >
              <p v-for="(item, index) of stationList" :key="index">
                <el-option :label="item" :value="item" se></el-option>
              </p>
            </el-select>
          </el-form-item>
          <el-form-item>
            <p slot="label" class="miniLabel">时间段</p>
            <el-date-picker
              v-model="timePickerDay"
              type="daterange"
              value-format="yyyy-MM-dd"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <p class="searchBtns">
              <el-button type="success" class="greenBtn" @click="getChartsData"
                >筛选</el-button
              >
              <el-button
                type="success"
                class="greenBtn"
                @click="openExportOption"
                >导出</el-button
              >
            </p>
          </el-form-item>
        </el-form>
      </div>
      <div>
        <div class="tubiao showType">
          <div class="title" style="border-bottom: 1px solid #eee">
            日均值数据
            <el-radio-group
              v-model="mintype"
              size="small"
              @change="showTypeAction"
              style="margin-left: 12px"
            >
              <el-radio-button label="图表"></el-radio-button>
              <el-radio-button label="表格"></el-radio-button>
            </el-radio-group>
          </div>
        </div>
        <div class="dataChartCnt" v-if="mintype === '图表'">
          <div class="dataChartBox">
            <div
              class="chart"
              v-for="(option, index) in lineOptions"
              :key="index"
              v-show="option.show"
            >
              <el-button
                size="mini"
                class="openchart"
                @click="openDetailChart(option)"
              >
                <i class="iconfont iconquanping"></i>
              </el-button>
              <lineChart :option="option" :isShow="option.show"></lineChart>
            </div>
            <p class="noData" v-show="!isMeanNoData">暂无数据</p>
          </div>
        </div>
        <div class="tableList" v-show="mintype === '表格'">
          <tableList
            :hisDataList="avgDatas"
            :factorField="factorField"
            :factorStatus="factorStatus"
            :type="'day'"
            :standard="standard"
            :dataTypeShow="'hour'"
          ></tableList>
          <v-paging
            @setCurrent="setNum"
            @setCurren="setPage"
            :total="totalpage"
          />
        </div>
      </div>
    </div>
    <!-- 导出表格配置 -->
    <el-dialog :visible.sync="exportExcelVisible" append-to-body>
      <div slot="title">
        <p>导出表格</p>
      </div>
      <el-form :model="searchForm" size="mini" label-width="90px">
        <el-row>
          <el-form-item label="水站：">
            <el-select
              v-model="searchForm.watersmeantation"
              placeholder="请选择需要导出的水站"
              style="width: 80%"
            >
              <el-option
                v-for="station in stationList"
                :key="station"
                :label="station"
                :value="station"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item>
            <p slot="label" class="miniLabel">时间段</p>
            <el-date-picker
              v-model="timePickerDay"
              type="daterange"
              value-format="yyyy-MM-dd"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions"
            ></el-date-picker>
          </el-form-item>
        </el-row>
        <el-form-item label>
          <el-button type="primary" @click="exportExcel">导出</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters, mapActions } from "vuex";
import lineChart from "../components/charts.vue";
import common from "@/plugins/common";
import myPaging from "@/components/myPaging.vue";
import tableList from "@/components/tableList.vue";
import { meanRate, meanRateDownload } from "@/http/api";
export default {
  data() {
    return {
      timePickerDay: [],
      searchForm: {
        isExcel: "no",
        watersmeantation: "",
      },
      hisLoading: true,
      mintype: "图表", //表格图表切换
      lineOptions: {},
      detailChartVisible: false,
      detailChart: null,
      standard: {},
      avgDatas: [],
      searchResult: {},
      factorField: [],
      factorStatus: {},
      currentPage: 1,
      totalpage: 0,
      pageSize: 12,
      isMeanNoData: true,
      exportExcelVisible: false,
      pickerOptions: {
        disabledDate: (time) => {
          return time.getTime() > Date.now();
        },
      },
    };
  },
  async created() {
    await this.getStationListName({ dataType: null });
    this.searchForm.watersmeantation = this.stationList
      ? this.stationList[0]
      : "沙江4#";
    this.timePickerDay = [
      common.changeDateToString(new Date(new Date().getTime() - 518400000)),
      common.changeDateToString(new Date()),
    ];
    this.showTypeAction();
  },
  components: {
    lineChart,
    tableList,
  },
  computed: {
    ...mapGetters({
      stationList: "getStationList",
    }),
  },
  methods: {
    ...mapActions(["getStationListName"]),
    //打开全屏
    openDetailChart(option) {
      this.detailChartVisible = true;
      this.$nextTick(() => {
        this.detailChart = this.$echarts.init(
          document.getElementById("deatailChart")
        );
        this.initDeatailChart(option);
      });
    },
    //设置全屏图表
    initDeatailChart(option) {
      let chartOption = {
        xAxis: {
          type: "category",
          data: option.xAxis.data,
        },
        yAxis: {
          type: "value",
        },
        series: option.series,
        title: {
          left: "center",
          text: option.title.text,
        },
        show: true,
        toolbox: {
          feature: {
            dataZoom: {
              yAxisIndex: false,
            },
            saveAsImage: {
              pixelRatio: 2,
            },
          },
        },
      };
      this.detailChart.setOption(chartOption);
    },
    // 筛选
    getChartsData() {
      this.submitSearch();
    },
    /**
     * 日均分析值
     *  */
    showTypeAction() {
      this.submitSearch();
    },
    //图表获取数据
    async submitSearch(pageOption = { pageSize: this.pageSize, pageNum: 1 }) {
      this.hisLoading = true;
      let params = {
        starttime: this.timePickerDay[0] + " 00:00:00",
        lasttime: this.timePickerDay[1] + " 23:59:59",
        waterstation: this.searchForm.watersmeantation,
        isExcel: "no",
      };
      if (this.mintype === "图表") {
        await meanRate(params).then((res) => {
          if (res.data) {
            // this.searchResult = [];
            // this.meanRate = res.data.avgDatas;
            // this.configLineChart();
            // let res = await getHistoricalData(params);
            this.searchResult = res.data;
            this.configLineChart();
          }
        });
      } else if (this.mintype === "表格") {
        await meanRate({ ...params, ...pageOption }).then((res) => {
          if (res.data) {
            this.totalpage = res.data.totalpage;
            this.avgDatas = [];
            this.factorField = [];
            res.data.avgDatas.push(res.data.min);
            res.data.avgDatas.push(res.data.max);
            res.data.avgDatas.push(res.data.avg);

            this.$nextTick().then(() => {
              this.avgDatas = res.data.avgDatas;
              res.data.factorMessage.forEach((item) => {
                if (Object.keys(res.data.factorField).includes(item.name)) {
                  this.standard[res.data.factorField[item.name]] =
                    item.standardValue;
                  this.factorField.push({
                    prop: res.data.factorField[item.name],
                    label: item.name + (item.name === "pH" ? "" : " mg/L"),
                    devStatus: item.name,
                    standardValue: item.standardValue,
                    factorLimit:
                      item.name === "pH"
                        ? "±" + item.factorLimit + "L"
                        : item.factorLimit + "L",
                  });
                }
              });
              this.factorStatus = res.data.factorStatus;
            });
          }
        });
      }
      this.hisLoading = false;
    },
    configLineChart() {
      let chartData = this.searchResult.avgDatas || [];
      let newOptions = {};
      let translate = {};
      let standard = {};
      let lineOptions = {};
      this.searchResult.factorMessage.forEach((item, index) => {
        if (this.searchResult.factorField[item.name]) {
          translate[this.searchResult.factorField[item.name]] = item.name;
          standard[this.searchResult.factorField[item.name]] =
            item.standardValue;
          newOptions[this.searchResult.factorField[item.name]] = new Array();
          lineOptions[this.searchResult.factorField[item.name]] = {};
        }
        if (this.searchResult.factorMessage.length - 1 === index) {
          newOptions["xAxis"] = new Array();
        }
      });
      for (let i = 0, len = chartData.length; i < len; i++) {
        for (var key in newOptions) {
          if (key !== "xAxis") {
            newOptions[key].push(chartData[i][key]);
          } else {
            newOptions[key].push(chartData[i].gmtMonitor);
          }
        }
      }
      let defaultOption = {
        show: true,
        grid: {
          left: "11%",
        },
        title: {
          // text: 'pH/总磷',
          left: "center",
          top: 10,
          textStyle: {
            fontSize: 14,
          },
        },
        tooltip: {
          trigger: "axis",
        },
        xAxis: {
          // data: newOptions.xAxis,
          type: "category",
          axisLabel: {
            formatter: (value) => value.replace(/ /, "\n"),
          },
          axisTick: {
            inside: true,
            alignWithLabel: true,
          },
        },
        yAxis: {
          name: "mg/L",
          splitLine: {
            show: false,
          },
          axisTick: {
            inside: true,
          },
        },
        series: [
          {
            type: "line",
            stact: "总量",
            smooth: true,
            large: true,
            data: newOptions.ph,
            areaStyle: {},
            itemStyle: {},
          },
        ],
      };

      let optionColor = {
        ph: "#A3A6F6",
        COD: "#F47FC1",
        ammoniaNitrogen: "#5BB0F0",
        phosphorus: "#FF8282",
        nitrogen: "#F0D65B",
        nickel: "#67EBAB",
        cuprum: "#F09C5B",
        chromium: "#5DD3EC",
        prussiate: "#D4A3F6",
        zinc: "#5BF0E6",
        realFlow: "#5DD3EC",
        orp: "#5BF0E6",
        uv254: "#5BF0E6",
        cumulativeFlow: "#D4A3F6",
      };
      this.$nextTick(() => {
        for (let i in lineOptions) {
          lineOptions[i] = common.deepClone(defaultOption);
          lineOptions[i].series[0].itemStyle.color = optionColor[i];
          lineOptions[i].series[0].areaStyle = {
            color: new this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: optionColor[i],
              },
              {
                offset: 1,
                color: "rgb(255, 255, 255)",
              },
            ]),
          };
          lineOptions[i].title.text = translate[i];
          lineOptions[i].xAxis.data = newOptions.xAxis.reverse();
          lineOptions[i].series[0].data = newOptions[i];
          lineOptions[i].series[0].name = translate[i];
          lineOptions[i].series[0].markLine = {
            name: translate[i],
            silent: true,
            large: true,
            symbol: "none",
            data: [
              {
                yAxis: standard[i],
              },
            ],
            label: {
              position: "end",
              // formatter: '标准线:{c}'
            },
            lineStyle: {
              color: "#e46f6f",
            },
          };

          lineOptions[i].show =
            newOptions[i].filter((d) => d !== null).length > 0;
        }

        // ph special handle
        if (lineOptions["ph"]) {
          lineOptions["ph"].yAxis.max = 14; //ph
          lineOptions["ph"].yAxis.maxInterval = 2;
          lineOptions["ph"].yAxis.name = "";
          lineOptions["ph"].series[0].markLine.data = [
            {
              yAxis: standard["ph"].split("~")[1],
            },
            {
              yAxis: standard["ph"].split("~")[0],
            },
          ];
        }
        if (lineOptions["orp"]) {
          lineOptions["orp"].yAxis.name = "mV";
        }
        if (lineOptions["uv254"]) {
          lineOptions["uv254"].yAxis.name = "AU/cm";
        }
        if (lineOptions["realFlow"]) {
          lineOptions["realFlow"].yAxis.name = "m³/s";
        }
        if (lineOptions["cumulativeFlow"]) {
          lineOptions["cumulativeFlow"].yAxis.name = "10⁴m³/h";
        }
        this.isMeanNoData = Object.values(lineOptions)
          .map((v) => v.show)
          .includes(true);
        this.lineOptions = lineOptions;
      });
    },
    //表格配置
    tableRowStyle({ rowIndex }) {
      if (rowIndex % 2 > 0) {
        return {
          backgroundColor: "#f6f6f6",
        };
      } else {
        return {
          backgroundColor: "#fff",
        };
      }
    },
    //设置条数
    setNum(val) {
      this.pageSize = val;
      this.submitSearch({ pageSize: this.pageSize, pageNum: this.currentPage });
    },
    //设置页数
    setPage(val) {
      this.currentPage = val;
      this.submitSearch({ pageSize: this.pageSize, pageNum: this.currentPage });
    },
    openExportOption() {
      this.exportExcelVisible = true;
    },
    async exportExcel() {
      const message = this.$message({
        message: "正在导出数据, 请稍后",
        duration: 0,
      });
      var params = {
        starttime: this.timePickerDay[0] + " 00:00:00",
        lasttime: this.timePickerDay[1] + " 23:59:59",
        waterstation: this.searchForm.watersmeantation,
        isExcel: "yes",
      };
      this.searchForm.isExcel = "yes";
      await meanRateDownload(params).then((res) => {});
      this.searchForm.isExcel = "no";
      // await this.submitSearch()
      message.close();
    },
  },
};
</script>

<style scoped>
.el-dialog__footer {
  display: flex;
  justify-content: center;
}

.newTest {
  min-height: 100%;
}

.newTest .title {
  position: relative;
  font-size: 16px;
  background: #ffffff;
  padding-left: 30px;
  line-height: 70px;
}

.newTest .title::before {
  content: "";
  position: absolute;
  left: 15px;
  width: 4px;
  height: 24px;
  top: 24px;
  background-color: #2399ff;
}

.searchBox {
  padding: 20px;
  padding-bottom: 10px;
  margin-bottom: 20px;
  background-color: #fff;
  display: flex;
}

.searchBox .miniLabel {
  line-height: 0;
}

.searchBtns {
  margin-top: 19px;
}

.el-dialog {
  z-index: 3000 !important;
}
.noData {
  width: 100%;
  line-height: 60px;
  text-align: center;
  color: #909399;
}
/* 因子 */
.dataChartCnt {
}

.dataChartBox {
  display: flex;
  flex-flow: row wrap;
  /* justify-content: space-between; */
  justify-content: flex-start;
  width: 100%;
  background: #ffffff;
  padding: 20px;
  box-sizing: border-box;
}

.dataChartBox .chart {
  position: relative;
  width: 31%;
  margin: 0 1%;
  height: 300px;
  min-height: 300px;
  background: #fff;
  margin-bottom: 20px;
}

.dataChartBox .chart .openchart {
  position: absolute;
  right: 12px;
  top: 12px;
  z-index: 1;
}

.deatailChartCnt {
  width: 100%;
  height: 450px;
}

.deatailChartCnt .deatailChart {
  width: 100%;
  height: 100%;
}
/* 日均分析值 */
.showType {
  background-color: #fff;
  padding: 16px;
  padding-top: 30px;
}
.tableList {
  background: #fff;
  padding: 20px;
}
</style>
